<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1">
        <title>二分查找法</title>
    </head>
    <body>
        <h1>方法一</h1>
        <pre class="language-JavaScript">
            <code>
                function binarySearch(arr, target) {
                    let l = 0, r = arr.length - 1; //[l, ...r]
                    while(l <= r) {
                        let mid = l + ((r - l) / 2) >> 0;
                        if(arr[mid] === target) {
                            return mid;
                        }
                        if(arr[mid] > target) {
                            r = mid - 1;
                        } else {
                            l = mid + 1;
                        }
                    }
                    return -1;
                }
            </code>
        </pre>
        <h1>方法二</h1>
        <pre class="language-JavaScript">
            <code>
                function binarySearch(arr, target) {
                    let l = 0, r = arr.length;//[l, ..., r)
                    while(l < r) {
                        let mid = l + ((r - l - 1) / 2) >> 0;
                        if(arr[mid] === target) {
                            return mid;
                        }
                        if(arr[mid] > target) {
                            r = mid;
                        } else {
                            l = mid + 1;
                        }
                    }
                    return -1;
                }
            </code>
        </pre>
        <script>
            function binarySearch(arr, target) {
                let l = 0, r = arr.length - 1; //[l, ...r]
                while(l <= r) {
                    let mid = l + ((r - l) / 2) >> 0;
                    if(arr[mid] === target) {
                        return mid;
                    }
                    if(arr[mid] > target) {
                        r = mid - 1;
                    } else {
                        l = mid + 1;
                    }
                }
                return -1;
            }
            function binarySearch1(arr, target) {
                let l = 0, r = arr.length;//[l, ..., r)
                while(l < r) {
                    let mid = l + ((r - l - 1) / 2) >> 0;
                    if(arr[mid] === target) {
                        return mid;
                    }
                    if(arr[mid] > target) {
                        r = mid;
                    } else {
                        l = mid + 1;
                    }
                }
                return -1;
            }
        </script>
    </body>
</html>